package com.brian.springsecurity.service.impl;

import com.brian.springsecurity.entity.Permission;
import com.brian.springsecurity.entity.User;
import com.brian.springsecurity.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: architect
 * @author: Brian Huang
 * @create: 2019-08-05 21
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        //底层会根据数据库查询用户信息，判断密码是否正确
        User user = userMapper.findByUsername(userName);
        // 3. 给用户设置权限
        List<Permission> listPermission = userMapper.findPermissionByUsername(userName);
        System.out.println("username:" + userName + ",对应权限:" + listPermission.toString());
        if (listPermission != null && listPermission.size() > 0) {
            // 定义用户权限
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            for (Permission permission : listPermission) {
                authorities.add(new SimpleGrantedAuthority(permission.getPermTag()));
            }
            user.setAuthorities(authorities);
        }
        return user;
    }
}
